package com.qf.dao.impl;

import com.qf.dao.GoodsTypeDao;
import com.qf.domain.GoodsType;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:liuXin
 * time:2024/4/16 11:09
 * description:
 */
public class GoodsTypeDaoImpl implements GoodsTypeDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public List<GoodsType> select(int level) {
        String sql=" SELECT `id`,`name`,`level`,`parent` FROM db_shopping.`tb_goods_type` WHERE `level`=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(GoodsType.class),level);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public GoodsType selectById(Integer typeId) {
        String sql=" SELECT `id`,`name`,`level`,`parent` FROM db_shopping.`tb_goods_type` WHERE `id`=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(GoodsType.class),typeId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> selectName() {
        String sql=" SELECT `name` FROM db_shopping.`tb_goods_type` where level=1 ";
        try {
            return queryRunner.query(sql,new ColumnListHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        String sql = " delete  from  db_shopping.tb_goods_type where id=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GoodsType> findAll() {
        try {
            return queryRunner.query("select * from db_shopping.tb_goods_type",new BeanListHandler<>(GoodsType.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
